package com.gigi.service.manual;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gigi.entity.AppealEntity;
import com.gigi.entity.FileEntity;
import com.gigi.entity.UserEntity;
import com.gigi.enums.ErrorCodeEnum;
import com.gigi.enums.YesOrNoEnum;
import com.gigi.mapper.generated.AppealMapper;
import com.gigi.model.AppealDO;
import com.gigi.model.ListAppealRequest;
import com.gigi.service.generated.AppealService;
import com.gigi.service.generated.FileService;
import com.gigi.service.generated.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AppealManageService {

    private final AppealService appealService;
    private final AppealMapper appealMapper;
    private final UserService userService;
    private final FileService fileService;

    public AppealManageService(AppealService appealService, AppealMapper appealMapper, UserService userService, FileService fileService) {
        this.appealService = appealService;
        this.appealMapper = appealMapper;
        this.userService = userService;
        this.fileService = fileService;
    }

    /**
     * 列表接口
     *
     * @param request
     * @return
     */
    public MultiResponse<AppealDO> list(ListAppealRequest request) {
        LambdaQueryWrapper<AppealEntity> wrapper = new LambdaQueryWrapper<AppealEntity>()
                .eq(Objects.nonNull(request.getState()), AppealEntity::getState, request.getState())
                .orderByDesc(AppealEntity::getId);
        Page<AppealEntity> page = new Page<>(request.getPageNum(), request.getPageSize());
        Page<AppealEntity> appealEntityPage = appealMapper.selectPage(page, wrapper);
        if (CollUtil.isEmpty(appealEntityPage.getRecords())) {
            return MultiResponse.ofWithoutTotal(Collections.emptyList());
        }

        List<AppealDO> appealDOS = appealEntityPage.getRecords().stream().map(e -> {
            UserEntity userEntity = userService.getById(e.getUserId());
            AppealDO appealDO = new AppealDO();
            appealDO.setId(e.getId());
            appealDO.setName(userEntity.getName());
            appealDO.setPhone(userEntity.getPhone());
            appealDO.setPic(userEntity.getPic());
            appealDO.setState(e.getState());
            appealDO.setTime(DateUtil.format(e.getTime(), DatePattern.NORM_DATETIME_MINUTE_PATTERN));
            appealDO.setUserId(e.getUserId());
            return appealDO;
        }).collect(Collectors.toList());
        return MultiResponse.of(appealDOS, (int) appealEntityPage.getTotal());
    }

    /**
     * 保存接口
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Response save(AppealDO request) {
        // 新增
        if (Objects.isNull(request.getId())) {
            if (Objects.isNull(request.getUserId())) {
                return Response.buildFailure(ErrorCodeEnum.PARAM_ERROR.getErrCode(), ErrorCodeEnum.PARAM_ERROR.getErrDesc());
            }

            // 已提交过申诉校验
            LambdaQueryWrapper<AppealEntity> wrapper = new LambdaQueryWrapper<AppealEntity>()
                    .eq(AppealEntity::getUserId, request.getUserId())
                    .eq(AppealEntity::getState, YesOrNoEnum.NO.getCode());
            AppealEntity appealEntity = appealService.getOne(wrapper, false);
            if (Objects.nonNull(appealEntity)) {
                return Response.buildFailure(ErrorCodeEnum.ALREADY_APPEAL.getErrCode(), ErrorCodeEnum.ALREADY_APPEAL.getErrDesc());
            }

            AppealEntity entity = new AppealEntity();
            entity.setUserId(request.getUserId());
            entity.setTime(LocalDateTime.now());
            if (!appealService.save(entity)) {
                return Response.buildFailure(ErrorCodeEnum.SAVE_FAILED.getErrCode(), ErrorCodeEnum.SAVE_FAILED.getErrDesc());
            }

            // 审核
        } else {
            // 审核通过
            AppealEntity entity = new AppealEntity();
            entity.setId(request.getId());
            entity.setState(YesOrNoEnum.YES.getCode());
            if (!appealService.updateById(entity)) {
                return Response.buildFailure(ErrorCodeEnum.EDIT_FAILED.getErrCode(), ErrorCodeEnum.EDIT_FAILED.getErrDesc());
            }

            // 删除违规图片
            AppealEntity appealEntity = appealService.getById(request.getId());
            LambdaQueryWrapper<FileEntity> wrapper = new LambdaQueryWrapper<FileEntity>()
                    .eq(FileEntity::getUserId, appealEntity.getUserId())
                    .eq(FileEntity::getState, YesOrNoEnum.YES.getCode());
            if (!fileService.remove(wrapper)) {
                return Response.buildFailure(ErrorCodeEnum.BIZ_EXCEPTION.getErrCode(), ErrorCodeEnum.BIZ_EXCEPTION.getErrDesc());
            }

        }
        return Response.buildSuccess();
    }

}
